/**
 * Project Name : APP
 * File Name : DealController.java
 * Package Name : cn.weixin.interceptor.controller
 * Date : 2015-3-4下午5:00:36
 */
package cn.weixin.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.weixin.service.core.CoreService;

/**
 * ClassName : DealController Use : TODO. date : 2015-3-4 下午5:00:36
 * 
 * @author Han
 * @version
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/weixin")
public class DealController {
	private static Logger log = LoggerFactory.getLogger(DealController.class);
	
	@Autowired
	private CoreService coreService;
	
	@RequestMapping(method = { RequestMethod.POST })
	@ResponseBody
	public void excute(HttpServletRequest request, HttpServletResponse response) {
		try {
			InputStream is = request.getInputStream();
			if (is != null) {
				// 获取微信消息
				StringBuilder xmlMsg = new StringBuilder();
				byte[] b = new byte[4096];
				for (int n; (n = is.read(b)) != -1;) {
					xmlMsg.append(new String(b, 0, n, "UTF-8"));
				}
				log.info("xml:" + xmlMsg);
				String outXml = coreService.excute(xmlMsg.toString());
				log.info(outXml);
				response.getWriter().print(outXml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().print("success");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 用于修改配置
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = { RequestMethod.GET })
	@ResponseBody
	public void excuteCheck(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.getWriter().print(request.getParameter("echostr"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
